<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="种类" prop="kind">
        <el-select v-model="queryParams.kind" placeholder="请选择种类" clearable style="width: 180px;">
          <el-option
            v-for="item in kindOptions"
            :key="item.id"
            :label="item.kind"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['administration:administration:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['administration:administration:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['administration:administration:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['administration:administration:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="administrationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="受理事项" align="center" prop="item" />
      <el-table-column label="审批编号" align="center" prop="number" />
      <el-table-column label="申请单位" align="center" prop="film" />
      <el-table-column label="办结日期" align="center" prop="date" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="办理状态" align="center" prop="state" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['administration:administration:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['administration:administration:remove']"
          >删除</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改审批管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="受理事项" prop="item">
          <el-input v-model="form.item" placeholder="请输入受理事项" />
        </el-form-item>
        <el-form-item label="审批编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入审批编号" />
        </el-form-item>
        <el-form-item label="申请单位" prop="film">
          <el-input v-model="form.film" placeholder="请输入申请单位" />
        </el-form-item>


        <el-form-item label="办结日期" prop="date">
          <el-date-picker clearable
            v-model="form.date"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择办结日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="canAudit" label="办理状态" prop="state">
          <el-input v-model="form.state" placeholder="请输入办理状态"/>
        </el-form-item>
        <el-form-item label="责任编辑" prop="writer">
          <el-input v-model="form.writer" placeholder="请输入责任编辑" />
        </el-form-item>

        <!-- 获取当前日期，不需要手动添加 -->
        <el-form-item label="发布日期" prop="pubdate"  v-if="false">
          <el-date-picker clearable
            v-model="form.pubdate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发布日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="点击量" prop="click">
          <el-input v-model="form.click" placeholder="请输入点击量" />
        </el-form-item>
        <el-form-item label="来源" prop="origin">
          <el-input v-model="form.origin" placeholder="请输入来源" />
        </el-form-item>
        <el-form-item v-if="canAudit" label="审批种类" prop="kind">
          <el-select
            clearable
            filterable
            v-model="form.kind" placeholder="请选择种类">
            <el-option
              placeholder="请选择种类"
              v-for="item in kindOptions"
              :key="item.id"
              :label="item.kind"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- 新增直接上传文件 -->
        <el-form-item label="文件路径" prop="filePath" v-if="!this.isEdit">
          <input type="file" @change="handlefilePathUpload" ref="filePathInput">
          <div v-if="isfilePathSelected">已选文件：{{ this.filePath.name }}</div>
        </el-form-item>
        <!-- 修改时可以预览文件 -->
        <el-form-item label="文件路径" prop="filePath" v-if="this.isEdit">
          <input type="file" @change="handleUpdateFilePath" ref="updateFilePathInput">
          <div v-if="originalFilePath">当前文件：{{ originalFilePath }}</div>
          <div v-if="updateFilePath">新选文件：{{ updateFilePath.name }}</div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAdministration, getAdministration, delAdministration,
  addAdministration, updateAdministration,addAdministration1,updatefilePath,logicDelAdministration } from "@/api/administration/administration";
import { getKind, listKind } from "../../../api/kind/kind";



export default {
  name: "Administration",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审批管理表格数据
      administrationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        kind: null
      },
      // 表单参数
      form: {},
      canAudit: false,
      // 审批类型列表
      kindOptions: [],
      originalFilePath : '',//文件路径
      filePath : '',//文件路径
      isEdit: false,//是否是编辑
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getKindList();
  },

  computed: {
    isfilePathSelected() {
      return this.filePath instanceof File;
    },
  },

  methods: {
    handlefilePathUpload(event){
      const file = event.target.files[0];
      this.filePath = file;
    },
    // 处理修改时的文件上传
    handleUpdateFilePath(event) {
      const file = event.target.files[0];
      this.updateFilePath = file;
    },

    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    getKindList() {
      listKind().then(response => {
        this.kindOptions = response.rows;
      });
    },


    /** 查询审批管理列表 */
    getList() {
      this.loading = true;
      listAdministration(this.queryParams).then(response => {
        const { rows, total }=response.data;
        this.canAudit=response.canAudit;
        this.administrationList = rows.map(item=>{
          const kindOption = this.kindOptions.find(col=>col.id===item.kind);
          return {
            ...item,
            kindName: kindOption ? kindOption.kind : '未知种类'
          }
        })
        this.total = total;
        this.loading = false;
      });
    },
    // 取消按钮
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      if (this.$refs.filePathInput) {
        this.$refs.filePathInput.value = '';
      }
      this.filePath = null;
      if (this.$refs.updateFilePathInput) {
        this.$refs.updateFilePathInput.value = '';
      }
      this.updateFilePath = null;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        item: null,
        number: null,
        film: null,
        date: null,
        state: null,
        writer: null,
        pubdate: null,
        click: null,
        origin: null,
        kind: null
      };
      this.filePath = null;
      this.updateFilePath = null;
      this.originalFilePath = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isEdit=false;

      //自动设置发布日期为当前时间
      const now=new Date();
      const formattedDate=this.formatDate(now);
      this.form.pubdate=formattedDate;

      this.form.writer="行政审批科"
      this.form.state='已办结';
      this.open = true;
      this.title = "添加审批管理";
      if (this.$refs.filePathInput) {
        this.$refs.filePathInput.value = '';
      }

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEdit = true;
      const id = row.id || this.ids;
      getAdministration(id).then(response => {
        this.form = response.data;
        if(this.form.kind != null)
          this.form.kind=Number(this.form.kind);
        if(!this.form.writer){
          this.form.writer=this.writer;
        }

        // 保存原始文件路径
        this.originalFilePath = this.form.filePath;

        this.open = true;
        this.title = "修改审批管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 修改操作
            if (this.updateFilePath) {
              // 如果有新文件，先上传文件
              const formData = new FormData();
              formData.append('file', this.updateFilePath);
              updatefilePath(this.form.id, formData).then(response => {
                // console.log('文件上传成功', this.from.id,formData);
                // 文件上传成功后，更新其他信息
                this.form.filePath = response.url;
                updateAdministration(this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              });
            } else {
              // 没有新文件，直接更新信息
              updateAdministration(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }
          } else {
            // 新增操作
            const formatData = new FormData();
            // 添加表单中的每个字段
            for (const key in this.form) {
              if (this.form[key] !== undefined && this.form[key] !== null) {
                formatData.append(key, this.form[key]);
              }
            }
            // 添加文件字段
            if (this.filePath) {
              formatData.append('filePath', this.filePath);
            }
            addAdministration1(formatData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除审批管理编号为"' + ids + '"的数据项？').then(function() {
        return logicDelAdministration(ids);
      }).then(() => {
        delAdministration(ids).then(response => {
          this.getList();
        });
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
        this.$modal.msgError("删除失败");
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('administration/administration/export', {
        ...this.queryParams
      }, `administration_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
